<?php

namespace App\Support;

class Components
{
    public static function make()
    {
        return new self();
    }
    

    /**
     * 流量图表组件
     * @param string $idField ID字段名称
     * @return mixed
     */
    public function trafficChart($type = '', $size = 'lg', $id = '', $month = '',$day = '')
    {

        return amis()->Chart()
            ->height($size == 'lg' ? 500 : 300)
            ->className('traffic-chart')
            ->showDownload(true)
            ->api([
                'method' => 'get',
                'url' => '/flowscharts',
                'data' => [
                    'timeRange' => '${timeRange}',
                    'switch_id' => '${switch.id}',
                    'switch_port_id' => '${port_index}',
                    'dataType' => '${dataType}',
                    'type' => $type,
                    'id' => $id,
                    'month' => '${month}',
                    'day' => $day
                ],
                'adaptor' => <<<EOT
                    if (!response.data || !response.data.flowData) {
                        return {
                            status: 2,
                            msg: '数据格式错误'
                        };
                    }
                    
                    // 将字节转换为 Gbps
                    // 这里需要判断dataType 根据dataType来处理进制 1000 还是 1024
                    const bytesToGbps = (bytes) => {
                        
                        if (response.data.dataType == 1000) {
                            return Number((bytes * 8 / (1000 * 1000 * 1000)).toFixed(2));
                        } else {
                            return Number((bytes * 8 / (1024 * 1024 * 1024)).toFixed(2));
                        }
                    };

                    
                    
                    // 计算统计数据
                    const calculateStats = (data) => {
                        const inbound = data.map(item => bytesToGbps(item.in_rates));
                        const outbound = data.map(item => bytesToGbps(item.out_rates));
                        
                        // 排序用于计算 95th
                        const sortedIn = [...inbound].sort((a, b) => a - b);
                        const sortedOut = [...outbound].sort((a, b) => a - b);
                        const pos = Math.floor(data.length * 0.95);
                        
                        return {
                            in_max: Math.max(...inbound),
                            in_avg: inbound.reduce((a, b) => a + b, 0) / inbound.length,
                            in_95th: sortedIn[pos],
                            out_max: Math.max(...outbound),
                            out_avg: outbound.reduce((a, b) => a + b, 0) / outbound.length,
                            out_95th: sortedOut[pos]
                        };
                    };
                    
                    const stats = calculateStats(response.data.flowData);
                    
                    const result = {
                        status: 0,
                        msg: '获取成功',
                        data: {
                            switch_name: response.data.switch_name || '',
                            port_name: response.data.port_name || '',
                            time_start: response.data.time_start || '',
                            time_end: response.data.time_end || '',
                            timeData: response.data.flowData.map(item => item.timeline_5min),
                            inData: response.data.flowData.map(item => bytesToGbps(item.in_rates)),
                            outData: response.data.flowData.map(item => bytesToGbps(item.out_rates)),
                            stats: stats,
                            legendData: [
                                "入口流量 | 最大:" + stats.in_max.toFixed(2) + " Gbps    平均:" + stats.in_avg.toFixed(2) + " Gbps    95th:" + (stats.in_95th * 1000).toFixed(2) + " Mbps",
                                "出口流量 | 最大:" + stats.out_max.toFixed(2) + " Gbps    平均:" + stats.out_avg.toFixed(2) + " Gbps    95th:" + (stats.out_95th * 1000).toFixed(2) + " Mbps"
                            ],
                            totalText: "入口流量 + 出口流量 95th: " + (Math.max(stats.in_95th, stats.out_95th) * 1000).toFixed(2) + " Mbps"
                        }
                    };

                    
                    
                    console.log('API Response:', result);
                    return result;
                EOT
            ])
            ->config([
                'theme' => 'light',
                'toolbox' => [
                    'show' => true,
                    'feature' => [
                        'saveAsImage' => [
                            'show' => true
                        ]
                    ]
                ],
                'title' => [
                    'text' => '${switch_name} - ${port_name} 流量图',
                    'subtext' => '${time_start} - ${time_end}',
                    'left' => 'center',
                    'textStyle' => [
                        'fontSize' => 16
                    ],
                    'subtextStyle' => [
                        'fontSize' => 14
                    ]
                ],
                'tooltip' => [
                    'trigger' => 'axis',
                    'axisPointer' => [
                        'type' => 'cross'
                    ],
                    'formatter' => '{b}<br/>入口流量: {c0} Gbps<br/>出口流量: {c1} Gbps'
                ],
                'legend' => [
                    [
                        'data' => '${legendData}',
                        'orient' => 'vertical',
                        'icon' => 'rect',
                        'textStyle' => [
                            'fontFamily' => 'Consolas,Monaco,monospace',
                            'fontSize' => 12
                        ],
                        'left' => '5%',
                        'bottom' => 50,
                        'itemGap' => 7
                    ],
                    [
                        'data' => [
                            [
                                'name' => '${legendData[0]}'
                            ]
                        ],
                        'itemStyle' => [
                            'color' => '#e56d6d'
                        ],
                        'icon' => 'diamond',
                        'orient' => 'vertical',
                        'textStyle' => [
                            'fontFamily' => 'Consolas,Monaco,monospace',
                            'fontSize' => 12
                        ],
                        'formatter' => '${totalText}',
                        'left' => '5%',
                        'bottom' => 30,
                        'itemGap' => 7
                    ]
                ],
                'grid' => [
                    'left' => '3%',
                    'right' => '4%',
                    'bottom' => 100,
                    'top' => 60,
                    'containLabel' => true
                ],
                'xAxis' => [
                    'type' => 'category',
                    'boundaryGap' => false,
                    'data' => '${timeData}',
                    'axisLabel' => [
                        'fontSize' => 10
                    ],
                    
                ],
                'yAxis' => [
                    'type' => 'value',
                    'name' => '流量(Gbps)',
                    'axisLabel' => [
                        'fontSize' => 10,
                        'formatter' => '{value}.00'
                    ]
                ],
                'series' => [
                    [
                        'name' => '${legendData[0]}',
                        'type' => 'line',
                        'data' => '${inData}',
                        'smooth' => true,
                        'symbol' => 'none',
                        'areaStyle' => [
                            'color' => [
                                'type' => 'linear',
                                'colorStops' => [
                                    ['offset' => 0, 'color' => 'rgba(32, 200, 59, 0.3)'],
                                    ['offset' => 1, 'color' => 'rgba(32, 200, 59, 0.1)']
                                ]
                            ]
                        ],
                        'itemStyle' => [
                            'color' => '#20c83b'
                        ],
                        
                        'markLine' => [
                            'silent' => true,
                            'lineStyle' => [
                                'color' => '#ff0000',
                                'type' => 'solid'
                            ],
                            'label' => [
                                'position' => 'insideEndTop',
                                'formatter' => '入口 95th: {c} Gbps',
                                'fontSize' => 12,
                                'padding' => [0, 0, 0, 40]
                            ],
                            'data' => [
                                [
                                    'yAxis' => '${stats.in_95th}',
                                    'name' => '入口95th'
                                ]
                            ]
                        ]
                    ],
                    [
                        'name' => '${legendData[1]}',
                        'type' => 'line',
                        'data' => '${outData}',
                        'smooth' => true,
                        'symbol' => 'none',
                        'areaStyle' => [
                            'color' => [
                                'type' => 'linear',
                                'colorStops' => [
                                    ['offset' => 0, 'color' => 'rgba(39, 129, 222, 0.3)'],
                                    ['offset' => 1, 'color' => 'rgba(39, 129, 222, 0.1)']
                                ]
                            ]
                        ],
                        'itemStyle' => [
                            'color' => '#2781de'
                        ],
                        'markLine' => [
                            'silent' => true,
                            'lineStyle' => [
                                'color' => '#ff0000',
                                'type' => 'solid'
                            ],
                            'label' => [
                                'position' => 'insideEndTop',
                                'formatter' => '出口 95th: {c} Gbps',
                                'fontSize' => 12,
                                'padding' => [0, 0, 0, 40]
                            ],
                            'data' => [
                                [
                                    'yAxis' => '${stats.out_95th}',
                                    'name' => '出口95th'
                                ]
                            ]
                        ]
                    ]
                ]
            ]);
    }

    /**
     * 流量图表组件 生成图表
     *
     * 
     */
    public function makeChart($type = '', $size = 'lg', $id = '', $month = '',$day = '')
    {

        return amis()->Chart()
            ->height($size == 'lg' ? 500 : 300)
            ->className('traffic-chart')
            ->showDownload(true)
            ->api([
                'method' => 'get',
                'url' => '/tools/flow-charts/data',
                'data' => [
                    'dataType' => '1000',
                ],
                'adaptor' => <<<EOT
                    if (!response.data || !response.data.flowData) {
                        return {
                            status: 2,
                            msg: '数据格式错误'
                        };
                    }
                    
                    // 将字节转换为 Gbps
                    // 这里需要判断dataType 根据dataType来处理进制 1000 还是 1024
                    const bytesToGbps = (bytes) => {
                        
                        if (response.data.dataType == 1000) {
                            return Number((bytes  / (1000 * 1000 * 1000)).toFixed(2));
                        } else {
                            return Number((bytes  / (1024 * 1024 * 1024)).toFixed(2));
                        }
                    };

                    
                    
                    // 计算统计数据
                    const calculateStats = (data) => {
                        const inbound = data.map(item => bytesToGbps(item.in_rates));
                        const outbound = data.map(item => bytesToGbps(item.out_rates));
                        
                        // 排序用于计算 95th
                        const sortedIn = [...inbound].sort((a, b) => a - b);
                        const sortedOut = [...outbound].sort((a, b) => a - b);
                        const pos = Math.floor(data.length * 0.95);
                        
                        return {
                            in_max: Math.max(...inbound),
                            in_avg: inbound.reduce((a, b) => a + b, 0) / inbound.length,
                            in_95th: sortedIn[pos],
                            out_max: Math.max(...outbound),
                            out_avg: outbound.reduce((a, b) => a + b, 0) / outbound.length,
                            out_95th: sortedOut[pos]
                        };
                    };
                    
                    const stats = calculateStats(response.data.flowData);
                    
                    const result = {
                        status: 0,
                        msg: '获取成功',
                        data: {
                            switch_name: response.data.switch_name || '',
                            port_name: response.data.port_name || '',
                            time_start: response.data.time_start || '',
                            time_end: response.data.time_end || '',
                            timeData: response.data.flowData.map(item => item.timeline_5min),
                            inData: response.data.flowData.map(item => bytesToGbps(item.in_rates)),
                            outData: response.data.flowData.map(item => bytesToGbps(item.out_rates)),
                            stats: stats,
                            legendData: [
                                "入口流量 | 最大:" + stats.in_max.toFixed(2) + " Gbps    平均:" + stats.in_avg.toFixed(2) + " Gbps    95th:" + (stats.in_95th * 1000).toFixed(2) + " Mbps",
                                "出口流量 | 最大:" + stats.out_max.toFixed(2) + " Gbps    平均:" + stats.out_avg.toFixed(2) + " Gbps    95th:" + (stats.out_95th * 1000).toFixed(2) + " Mbps"
                            ],
                            totalText: "入口流量 + 出口流量 95th: " + (Math.max(stats.in_95th, stats.out_95th) * 1000).toFixed(2) + " Mbps"
                        }
                    };

                    
                    
                    console.log('API Response:', result);
                    return result;
                EOT
            ])
            ->config([
                'theme' => 'light',
                'toolbox' => [
                    'show' => true,
                    'feature' => [
                        'saveAsImage' => [
                            'show' => true
                        ]
                    ]
                ],
                'title' => [
                    'text' => '${switch_name} - ${port_name} 流量图',
                    'subtext' => '${time_start} - ${time_end}',
                    'left' => 'center',
                    'textStyle' => [
                        'fontSize' => 16
                    ],
                    'subtextStyle' => [
                        'fontSize' => 14
                    ]
                ],
                'tooltip' => [
                    'trigger' => 'axis',
                    'axisPointer' => [
                        'type' => 'cross'
                    ],
                    'formatter' => '{b}<br/>入口流量: {c0} Gbps<br/>出口流量: {c1} Gbps'
                ],
                'legend' => [
                    [
                        'data' => '${legendData}',
                        'orient' => 'vertical',
                        'icon' => 'rect',
                        'textStyle' => [
                            'fontFamily' => 'Consolas,Monaco,monospace',
                            'fontSize' => 12
                        ],
                        'left' => '5%',
                        'bottom' => 50,
                        'itemGap' => 7
                    ],
                    [
                        'data' => [
                            [
                                'name' => '${legendData[0]}'
                            ]
                        ],
                        'itemStyle' => [
                            'color' => '#e56d6d'
                        ],
                        'icon' => 'diamond',
                        'orient' => 'vertical',
                        'textStyle' => [
                            'fontFamily' => 'Consolas,Monaco,monospace',
                            'fontSize' => 12
                        ],
                        'formatter' => '${totalText}',
                        'left' => '5%',
                        'bottom' => 30,
                        'itemGap' => 7
                    ]
                ],
                'grid' => [
                    'left' => '3%',
                    'right' => '4%',
                    'bottom' => 100,
                    'top' => 60,
                    'containLabel' => true
                ],
                'xAxis' => [
                    'type' => 'category',
                    'boundaryGap' => false,
                    'data' => '${timeData}',
                    'axisLabel' => [
                        'fontSize' => 10
                    ]
                ],
                'yAxis' => [
                    'type' => 'value',
                    'name' => '流量(Gbps)',
                    'axisLabel' => [
                        'fontSize' => 10,
                        'formatter' => '{value}.00'
                    ]
                ],
                'series' => [
                    [
                        'name' => '${legendData[0]}',
                        'type' => 'line',
                        'data' => '${inData}',
                        'smooth' => true,
                        'symbol' => 'none',
                        'areaStyle' => [
                            'color' => [
                                'type' => 'linear',
                                'colorStops' => [
                                    ['offset' => 0, 'color' => 'rgba(32, 200, 59, 0.3)'],
                                    ['offset' => 1, 'color' => 'rgba(32, 200, 59, 0.1)']
                                ]
                            ]
                        ],
                        'itemStyle' => [
                            'color' => '#20c83b'
                        ],
                        'markLine' => [
                            'silent' => true,
                            'lineStyle' => [
                                'color' => '#ff0000',
                                'type' => 'solid'
                            ],
                            'label' => [
                                'position' => 'insideEndTop',
                                'formatter' => '入口 95th: {c} Gbps',
                                'fontSize' => 12,
                                'padding' => [0, 0, 0, 40]
                            ],
                            'data' => [
                                [
                                    'yAxis' => '${stats.in_95th}',
                                    'name' => '入口95th'
                                ]
                            ]
                        ]
                    ],
                    [
                        'name' => '${legendData[1]}',
                        'type' => 'line',
                        'data' => '${outData}',
                        'smooth' => true,
                        'symbol' => 'none',
                        'areaStyle' => [
                            'color' => [
                                'type' => 'linear',
                                'colorStops' => [
                                    ['offset' => 0, 'color' => 'rgba(39, 129, 222, 0.3)'],
                                    ['offset' => 1, 'color' => 'rgba(39, 129, 222, 0.1)']
                                ]
                            ]
                        ],
                        'itemStyle' => [
                            'color' => '#2781de'
                        ],
                        'markLine' => [
                            'silent' => true,
                            'lineStyle' => [
                                'color' => '#ff0000',
                                'type' => 'solid'
                            ],
                            'label' => [
                                'position' => 'insideEndTop',
                                'formatter' => '出口 95th: {c} Gbps',
                                'fontSize' => 12,
                                'padding' => [0, 0, 0, 40]
                            ],
                            'data' => [
                                [
                                    'yAxis' => '${stats.out_95th}',
                                    'name' => '出口95th'
                                ]
                            ]
                        ]
                    ]
                ]
            ]);
    }


} 